<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Models\Comments;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CommentsController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
//        $page = ($data['page'] - 1) * $limit;
       $keyword=$request->input('keyword');
    $data=DB::table('comments')
        ->leftJoin('users','comments.users_id','=','users.id')
        ->leftJoin('products','comments.products_id','=','products.id')
        ->when($keyword,function($query) use($keyword){

//            $query->where('products.name','like',"%$keyword%")
//                ->orWhere('users.username','like',"%$keyword%")->get();

            $query->whereRaw('(concat(users.username,products.name) like "%' . $keyword . '%")');
        })
        ->select('users.username','products.name','comments.*')->paginate($request->input('limit',10));
//        ->offset($request->input('page',1))->limit($request->input('limit',10))
//        ->get()->each(function ($q){
//                $q->created_at=date('Y-m-d H:i',$q->created_at);
//        });
        foreach ($data as &$item){
            $item->created_at=date('Y-m-d H:i',$item->created_at);
        }

        return $this->success($data);

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        if(Comments::where('id',$id)->update($request->all())) return $this->success();
        $this->error();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(Comments::destroy($id)) return $this->success();
        $this->error();
    }


    public function updateStatus($id)
    {
        if(Comments::where('id',$id)->update(['status'=>\request()->input('status')])) return $this->success();

        $this->error();
    }
}
